<template>
  <div>
    <form action="/">
      <van-search
        v-model.trim="keywords"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        class="search-inp"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult = false"
      />
    </form>
    <!-- <search-history></search-history>
    <search-suggestions></search-suggestions>
    <search-result></search-result> -->
    <component
      :keywords="keywords"
      :is="componentName"
      @update-keywords="onSearch"
    ></component>
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestions from './components/SearchSuggestions.vue'
import SearchResult from './components/SearchResult.vue'
import {mapMutations,mapState} from 'vuex'
export default {
  components: {
    SearchHistory,
    SearchSuggestions,
    SearchResult
  },
  data() {
    return {
      keywords: '',
      isShowResult: false
    }
  },
  computed: {
    ...mapState(['histories']),
    componentName() {
      //搜索框没有内容时 渲染搜索历史
      if (this.keywords === '') {
        return 'SearchHistory'  
      }
      if (this.isShowResult) {
        return 'SearchResult'
      }
      return 'SearchSuggestions'
    }
  },
  methods: {
    ...mapMutations(['SET_HISTORIES']),
    onSearch(val) {
      //更新keywords结果
      this.keywords = val

      let newHistories = [this.keywords,...this.histories]
      newHistories = [...new Set(newHistories)]
      this.SET_HISTORIES(newHistories)
      //展示搜索结果
      this.isShowResult = true
    },
    onCancel() {
      //   thsi.$toast('取消')  

      //触发取消，先清空keyword在触发onCancel
      if(this.keywords === '') {
        // this.$router.back()
        this.$router.go(-1)
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-inp {
  .van-search__action {
    color: #fff;
  }
}
</style>
